package com.recommendation.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.lang.StringUtils;

import com.recommendation.taobao.TaobaoProxy;
import com.recommendation.utils.PagingResult;
import com.taobao.api.ApiException;
import com.taobao.api.domain.Item;
import com.taobao.api.request.ItemUpdateRequest;
import com.taobao.api.request.ItemsOnsaleGetRequest;
import com.taobao.api.response.ItemUpdateResponse;
import com.taobao.api.response.ItemsListGetResponse;
import com.taobao.api.response.ItemsOnsaleGetResponse;

public class TaobaoService {
	
	static Logger _logger = Logger.getLogger(TaobaoService.class.getName());
	
	public static final long PAGE_SIZE = 200;
	
	public List<Item> getOnsaleItems(String keyword, String fields, String order, String session) throws ApiException
	{
		List<Item> items = new ArrayList<Item>();
		ItemsOnsaleGetResponse rsp = getPage(keyword, fields, order, 1, session);
		if (rsp.isSuccess() && rsp.getItems() != null)
		{
			items.addAll(rsp.getItems());
			long total = rsp.getTotalResults();
			int pageCount = PagingResult.getPageCount(total, PAGE_SIZE);
			for (int i = 2; i <= pageCount; i++)
			{
				rsp = getPage(keyword, fields, order, i, session);
				if (rsp.isSuccess() && rsp.getItems() != null)
				{
					items.addAll(rsp.getItems());
				}
				else
				{
					_logger.warning(TaobaoProxy.getError(rsp));
				}
			}
		}
		return items;
	}
	
	public ItemsOnsaleGetResponse getPage(String keyword, String fields, String order, long pageNo, String session) throws ApiException
	{
		return getPage(keyword, fields, order, PAGE_SIZE, pageNo, session);
	}
	
	public ItemsOnsaleGetResponse getPage(String keyword, String fields, String order, long pageSize, long pageNo, String session) throws ApiException
	{
		ItemsOnsaleGetRequest req = new ItemsOnsaleGetRequest();
		if (keyword != null)
		{
			req.setQ(keyword);
		}
		req.setFields(fields);
		if (order != null)
		{
			req.setOrderBy(order);
		}
		req.setPageNo(pageNo);
		req.setPageSize(pageSize);
		return TaobaoProxy.createClient().execute(req, session);
	}
	
	public ItemUpdateResponse updatePeriod(long numIid, long period, String session) throws ApiException
	{
		ItemUpdateRequest req = new ItemUpdateRequest();
		req.setNumIid(numIid);
		req.setValidThru(period);
		 
		ItemUpdateResponse rsp = TaobaoProxy.createClient().execute(req, session);
		return rsp;
	}
	
	public List<Item> getItems(String numIids, String fields, String session) throws Exception
	{
		_logger.info("numIids: " + numIids);
		List<Item> items = new ArrayList<Item>();
		if (numIids != null && numIids.length() > 0)
		{
			String[] numIidArray = numIids.split(",");
			if (numIidArray != null && numIidArray.length > 0)
			{
				_logger.info("length: " + numIidArray.length);
				int pages = numIidArray.length / 20;
				if (numIidArray.length % 20 > 0)
				{
					++pages;
				}
				_logger.info("pages: " + pages);
				for (int i = 0; i < pages; i++)
				{
					int from = i * 20;
					int to = Math.min((i + 1) * 20, numIidArray.length);
					String[] page = Arrays.copyOfRange(numIidArray, from, to);
					if (page != null && page.length > 0)
					{
						String partialNumIids = StringUtils.join(page, ",");
						_logger.info("page: " + partialNumIids);
						try {
							ItemsListGetResponse rsp = TaobaoProxy.getItems(partialNumIids, fields, session);
							if (rsp.isSuccess())
							{
								List<Item> list = rsp.getItems();
								if (list != null)
								{
									items.addAll(list);
								}
							}
							else
							{
								_logger.warning(TaobaoProxy.getError(rsp));
								throw new Exception(rsp.getMsg());
							}
						} catch (ApiException e) {
							_logger.log(Level.SEVERE, "", e);
						}
					}
				}
			}
		}
		return items;
	}
	
	public static boolean contains(List<Item> items, Item item)
	{
		if (items != null)
		{
			for (Item item1 : items)
			{
				if (item1.getNumIid().longValue() == item.getNumIid().longValue())
				{
					return true;
				}
			}
		}
		return false;
	}
	
	public static List<Item> removeAll(List<Item> list1, List<Item> list2)
	{
		if (list2 != null)
		{
			Iterator<Item> it = list1.iterator();
			while (it.hasNext())
			{
				Item item = it.next();
				if (contains(list2, item))
				{
					_logger.info("exclude item: " + item.getTitle());
					it.remove();
				}
			}
		}
		return list1;
	}
}
